package com.xzx.producer;

import com.xzx.common.DateUtil;
import com.xzx.common.bean.CallLog;
import com.xzx.producer.bean.Contact;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Random;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2024/8/4 23:10
 */
public class Producer {
    private List<Contact> contacts;
    private PrintWriter printWriter;
    private volatile boolean running = true;

    public Producer(List<Contact> contacts, String outPath) throws IOException {
        this.contacts = contacts;
        this.printWriter = new PrintWriter(Files.newOutputStream(new File(outPath + "/call.log").toPath()));
    }

    public void start() {
        while (running) {
            int callerIndex = new Random().nextInt(contacts.size());
            int calleeIndex = new Random().nextInt(contacts.size());
            if (callerIndex == calleeIndex) {
                continue;
            }
            Contact caller = contacts.get(callerIndex);
            Contact callee = contacts.get(calleeIndex);

            CallLog callLog = new CallLog();
            callLog.setCaller(caller.getPhone());
            callLog.setCallee(callee.getPhone());
            int duration = new Random().nextInt(3000) + 1;
            callLog.setDuration(duration);

            long startBaseTs = 1704038400000L;// 2024-01-01
            callLog.setCallStartTime(DateUtil.formatDate(startBaseTs + (new Random().nextInt(31536000) * 1000L), "yyyyMMddHHmmss"));

            System.out.println(callLog);
            printWriter.println(callLog);
            printWriter.flush();

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        this.running = false;
    }
}
